package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author tang
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    private final CourseCategoryMapper courseCategoryMapper;
    public CourseCategoryServiceImpl(CourseCategoryMapper courseCategoryMapper) {
        this.courseCategoryMapper = courseCategoryMapper;
    }

    @Override
    public List<CourseCategoryTreeDto> selectTreeNodes(String id) {
        List<CourseCategoryTreeDto> treeNodes = courseCategoryMapper.selectTreeNodes(id);
        return getChildren(treeNodes, id);
    }

    public List<CourseCategoryTreeDto> getChildren(List<CourseCategoryTreeDto> list, String id) {
        return list.stream()
                .filter(p -> Objects.equals(p.getParentid(), id))
                .peek(f -> {
                    List<CourseCategoryTreeDto> children = getChildren(list, f.getId());
                    if (children.size() == 0) {
                        f.setChildrenTreeNodes(null);
                    } else {
                        f.setChildrenTreeNodes(children);
                    }
                }).collect(Collectors.toList());
    }
}
